package com.updesignsz.api.configuration;

import com.updesignsz.api.util.IpUtil;
import com.updesignsz.api.util.ResponseUtil;
import com.updesignsz.commom.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * TODO 打印终端请求的参数 拦截器
 * Created User: keres
 * Date: 2020/5/12 11:42
 */
@Component
public class InterceptorConfig implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger("stdout");



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Date start = new Date();
        request.getSession().setAttribute("InterceptorConfig_start_date" + request.getRequestedSessionId(), start);
        if (request.getRequestURI().contains("/api/")) {
            response.setContentType("application/json;charset=UTF-8");
            try {
                logger.info("-----------------------------------请求开始-----------------------------------------");
                logger.info("请求URL------->:" + request.getRequestURI());
                logger.info("请求类型------>:" + StringUtil.toString(request.getHeader("User-Agent")));
                logger.info("请求IP地址---->:" + IpUtil.getIpAddr(request));
                String body = ResponseUtil.getRequestStr(request);
                logger.info("请求参数---->:" + body);

                request.setAttribute("data", body);


            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            request.getSession().setAttribute("InterceptorConfig_systemlogin" + request.getRequestedSessionId(), null);
        } else {
            if (request.getRequestURI().contains("dist") || request.getRequestURI().contains("import") || request.getRequestURI().contains("download") || request.getRequestURI().contains("wechat")) {
                return true;
            }
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        if (request.getRequestURI().contains("/api/")) {
            Date end = new Date();
            Date start = (Date) request.getSession().getAttribute("InterceptorConfig_start_date" + request.getRequestedSessionId());
//            log.info(String.format("请求%s处理完毕，结束时间%s：", request.getRequestURI(), format.format(end)));

            if (start != null) {
                request.getSession().removeAttribute("InterceptorConfig_start_date" + request.getRequestedSessionId());
                long seconds = (end.getTime() - start.getTime()) / 1000;

//                log.info(String.format("此次请求花费时间（秒）：%s", seconds));
                logger.info(String.format("此次请求花费时间（秒）：%s", seconds));
                logger.info("-------------------------------请求结束---------------------------------");
                logger.info("");
                logger.info("");
                logger.info("");
                if (seconds > 10) {
                    logger.info("警告：超过10秒");
                } else if (seconds > 5) {
                    logger.info("警告：超过5秒");
                } else if (seconds > 3) {
                    logger.info("警告：超过3秒");
                }
                request.getSession().removeAttribute("InterceptorConfig_systemlogin" + request.getRequestedSessionId());

            }
        }
//        super.afterCompletion(request, response, handler, ex);
    }

}
